package study.web;


import study.pojo.User;
import study.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    private UserServiceImpl service=new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接受用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //获取复选框数据
        String remember = req.getParameter("remember");

        /*2.调用Mybatis完成查询*/
        //  2.1获取SqlSessionFactory对象
        /*String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
*/

        //  2.4调用方法
        User user = service.login(username, password);


        resp.setContentType("text/html;charset=utf-8");


        /*3.判断user是否为null*/
        if(user!=null){
            //登陆成功
            //判断复选框是否选中
            //当equal比较时有字符串，字符串放前面，防止变量为空报错
            if("1".equals(remember)){
                //勾选记住账号密码
                //1.创建Cookie对象
                Cookie c_username = new Cookie("username",username);
                Cookie c_password = new Cookie("password",password);

                //设置Cookie的存活时间
                c_username.setMaxAge(60*60*24*7);
                c_password.setMaxAge(60*60*24*7);

                //2.发送
                resp.addCookie(c_username);
                resp.addCookie(c_password);

            }


            //将登陆成功后的User对象存储到Session中
            HttpSession session = req.getSession();
            session.setAttribute("user",user);
            resp.sendRedirect("brand.html");

        }else{
            //登陆失败

            //存储错误信息到request
            req.setAttribute("login_msg","用户名或密码错误");

            //跳转到jsp页面
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
